function z = resid3v_taumax(X)
global betta depr sigma taumax N T
global kstart kistart transfer deductible lamda tauK0 Delta1 Delta2 depr k c1 c1ss nu betta taumax depr r Fkk T c c0 c1ss rss Fkkss lamda rnext c1next Fkknext

Delta1 = X(T+1);
Delta2 = - Delta1;
deductible = X(T+2);
transfer=0;

if size(X,1)>1
    X=X';
end
gamma = X(1:T);

options=optimset('TolFun',1e-20,'TolX',1e-20,'Disp','off','MaxFunEvals',1e5); 
gammass=fsolve('findgammass',0.5,options);
muss=lamda*((1+(Delta1+Delta2/lamda)*(1-sigma))*c1ss^(-sigma)-sigma*c1ss^(-sigma-1)*gammass*(1-rss*(1-taumax)));
options=optimset('TolFun',1e-20,'TolX',1e-20,'Disp','iter','MaxFunEvals',1e5); 

tauK0=taumax;
tauKt(1:T) = taumax;
tauKt = [tauKt taumax];

%period 0
c0 = c1(1);
r0 = r(1);

%periods t>0
ct = c1(2:T);
rt = r(2:T);

mu(1)=lamda*((1+(Delta1+Delta2/lamda)*(1-sigma))*c0^(-sigma)...
    -sigma*gamma(1)*c0^(-sigma-1)...
    + sigma*c0^(-sigma-1)*((Delta1*kistart(1)+Delta2*kistart(2))*(1+r0*(1-tauK0)-depr)+Delta1*(deductible-transfer)+Delta2*(deductible+transfer))); %FOC for consumption at time 0
mu(2:T)=lamda*((1+(Delta1+Delta2/lamda)*(1-sigma))*ct.^(-sigma)...
    +gamma(2:T)*(-sigma).*ct.^(-sigma-1)...
    -gamma(1:T-1)*(-sigma).*ct.^(-sigma-1).*(1+rt.*(1-taumax)-depr)); %FOC for consumption at t>0

munext = [mu(2:end) muss];
z(1:T) = - mu + betta*munext.*(1-depr+rnext) - gamma.*c1next.^(-sigma)*betta*(1-taumax).*Fkknext; %FOC for capital

%present value budget constraint for group 1 (at steady state from period T onwards)
z(T+1) = sum(betta.^[0:T-1].*c1.^(-sigma).*c1) + betta^T/(1-betta)*c1ss^(-sigma)*c1ss-c1(1)^(-sigma)*(kistart(1)*(1+r(1)*(1-tauK0)-depr)-transfer+deductible);

%FOC for lamda
z(T+2) = sum(betta.^[0:T-1].*(Delta2*c1.^(1-sigma)-mu.*c1))+betta^T/(1-betta)*(Delta2*c1ss^(1-sigma)-muss*c1ss);



